const express = require('express');
// 引入中间件
const bodyParser = require('body-parser');
const serveStatic = require('serve-static');
const cookieParser = require('cookie-parser');
const cors = require('cors');

const app = express();

class Rreponse {
  constructor(status, message, data) {
    this.status = status;
    this.message = message;
    this.data = data;
    this.timestamp = new Date().getTime();
  }
}

// 中间件使用
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(serveStatic('public'));
app.use(cookieParser());
app.use(cors({
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  "preflightContinue": false,
  "optionsSuccessStatus": 204
}))


app.get('/user/findById', (req, res) => {
  console.log(req.query);
  res.send('查询字符串传参');
})

app.get('/user/findById/:id', (req, res) => {
  console.log(req.params);
  res.send('动态传参')
})

app.post('/user/save', (req, res) => {
  console.log(req.body);
  res.json(new Rreponse(200, '保存成功', null))
})

app.get('/login', (req, res) => {
  res.cookie("name", "terry");
  res.send('登录成功');
})

app.get('/getInfo', (req, res) => {
  console.log(req.cookies);
  res.send('获取信息成功');
})

app.get('/user/findAll', (req, res) => {
  const users = [
    { id: 1, name: '张三', age: 12 },
    { id: 2, name: '李四', age: 13 },
    { id: 3, name: '王五', age: 14 },
  ]
  res.json(new Rreponse(200, 'success', users))
})

app.listen(3000, () => {
  console.log('3000端口服务已开启......');
})